package com.dingding.transfer.stamper.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.dingding.transfer.stamper.constant.ApprovalPara;
import com.dingding.transfer.stamper.dto.FingerAddReq;
import com.dingding.transfer.stamper.dto.FormComponent;
import com.dingding.transfer.stamper.entity.User;
import com.dingding.transfer.stamper.service.BusinessService;
import com.dingding.transfer.stamper.service.DingDingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author wangxiyuan
 * @description 指纹录入 钉钉回调
 * @createDate 2021/4/6 15:27
 **/
@Slf4j
@Component
public class FingerAddInstance implements TaskInstanceProcessor{
    @Autowired
    private DingDingService dingDingService;

    @Autowired
    private BusinessService businessService;

    @Override
    public boolean match(String name) {
        return StringUtils.contains(name, ApprovalPara.FINGER_INFO);
    }

    @Override
    public void handleTaskStart(JSONObject jsonObject) {
        log.info("指纹录入回调");
        // 定义的指纹录入的表单第一条为姓名，第二条为设备
        List<FormComponent> formDetails = dingDingService.getFormDetails(jsonObject.getString("corpId"),
                jsonObject.getString("processInstanceId"));
        if(CollectionUtil.isNotEmpty(formDetails)){
            String name = formDetails.get(0).getValue();
            String uuid = businessService.getDeviceId(formDetails.get(1).getValue());
            User userInfo = businessService.findUserInfo(name);
            if(userInfo == null){
                log.error("根据用户名{}没有找到对应的用户信息",name);
                return;
            }
            FingerAddReq fingerAddReq = new FingerAddReq();
            // 这里不适用钉钉提供的userId，使用user这张表的主键作为userid
            fingerAddReq.setUserId(userInfo.getSerialId().toString());
            fingerAddReq.setUuid(uuid);
            fingerAddReq.setUserName(name);
            businessService.fingerAdd(fingerAddReq);
        }
    }
}
